package com.kaifamiao.high.thread;

/**
 * @author lucien-ma
 * @date 2021/10/8
 * @apiNote
 */
public class Demo04 {
    public static void main(String[] args) {
        AddRunnable addRunnable = new AddRunnable();
        ReduceRunnable reduceRunnable = new ReduceRunnable();
        new Thread(addRunnable).start();
        new Thread(addRunnable).start();
        new Thread(reduceRunnable).start();
        new Thread(reduceRunnable).start();
        System.out.println(Calculate.getJ());
    }
}

class Calculate{
    private static int j;

    public static int getJ() {
        return j;
    }

    public static void add() {
        j++;
    }

    public static void reduce() {
        j--;
    }
}

class AddRunnable implements Runnable {

    @Override
    public void run() {
        try {
            Thread.currentThread().sleep(800);
            synchronized (Calculate.class) {
                Calculate.add();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ReduceRunnable implements Runnable {

    @Override
    public void run() {
        try {
            Thread.currentThread().sleep(800);
            synchronized (Calculate.class) {
                Calculate.reduce();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
